package session;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Create By IntelliJ IDEA
 *
 * @Author: jsonor
 * @Create-Time: 2017/10/10 10:15
 * @Description: 初识Session
 */
@WebServlet(name = "hello", urlPatterns = {"/helloSession"})
public class HelloSessionServlet extends HttpServlet {

  @Override
  protected void doGet(HttpServletRequest request,
      HttpServletResponse response)
      throws ServletException, IOException {

    // getSession，如果是用户第一次访问，那么服务器端会生成一个session
    HttpSession session = request.getSession();

    // 为一次对话中添加数据 (request.setAttribute)
    /**
     * 服务器端会存储用户的: JSESSIONID(唯一的)
     * JSESSIONID -> HashMap(session)
     */
    session.setAttribute("username", "Hello world session add object");
    // 当用户网页不关闭的时候，保持对话的情况下，可以存储用户的数据
    System.out.println("session id = " + session.getId());

    response.getWriter().println("hello session servlet");
  }
}
